﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;

namespace CM.Resources.SDK
{
    //
    // 摘要:
    //     提供HTTP客户端请求
    //
    public class HttpPost
    {
        private string strEncoding = "utf-8";

        public HttpPost() { }

        public HttpPost(string strEncoding) {
            this.strEncoding = strEncoding;
        }

        /// <summary>
        /// 获取请求对象
        /// </summary>
        /// <param name="URL">请求地址</param>
        /// <param name="boundary">参数分隔符</param>
        /// <returns></returns>
        private HttpWebRequest getRequest(string URL, string boundary)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.Method = "POST";
                request.KeepAlive = true;
                return request;
             }catch(Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 接收文件上传结果
        /// </summary>
        /// <param name="Request">请求对象</param>
        /// <returns></returns>
        private ReponseBean getResult(HttpWebRequest Request)
        {
            try { 
                HttpWebResponse response = (HttpWebResponse)Request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding)))
                {
                    string str = reader.ReadToEnd();
                    if (str == null || str == "") { return null; }
                    return JsonConvert.DeserializeObject<ReponseBean>(str);
                }
            }catch(Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="URL">请求地址</param>
        /// <param name="Data">文件数据</param>
        /// <returns>ReponseBean</returns>
        public ReponseBean Post(string URL, FileData FileData)
        {
            string boundary = Guid.NewGuid().ToString();
            HttpWebRequest Request = getRequest(URL, boundary);
            string boundary_end = string.Format("\r\n--{0}--\r\n" ,boundary);
            NameValueCollection Params = FileData.Params;

            //参数
            if (Params != null)
            {
                string format = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                foreach (string key in Params.Keys)
                {
                    string s = string.Format(format, key, Params[key]);
                    byte[] str_arr = Encoding.UTF8.GetBytes(s);
                    Request.GetRequestStream().Write(str_arr, 0, str_arr.Length);
                }
            }
            //文件
            string FileFormat = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"\"\r\nContent-Type: application/octet-stream\r\n\r\n";
            string FileStr = string.Format(FileFormat, FileData.InputName);
            byte[] FileByteArray = Encoding.UTF8.GetBytes(FileStr);
            Request.GetRequestStream().Write(FileByteArray, 0, FileByteArray.Length);
            Request.GetRequestStream().Write(FileData.Data, 0, FileData.Data.Length);
            //结束符
            byte[] arr = Encoding.UTF8.GetBytes(boundary_end);
            Request.GetRequestStream().Write(arr, 0, arr.Length);
            //接收数据
            return getResult(Request);
        }
    }
}
